//
//  WSForumViewController.m
//  RunningMan
//
//  Created by 王帅 on 16/5/18.
//  Copyright © 2016年 WSJ. All rights reserved.
//

#import "WSForumViewController.h"
#import "WSForumTableViewCell.h"
#import "WSMyTool.h"
#import "WSAFNetWorkingTool.h"
#import "WSForumDetailsViewController.h"
@interface WSForumViewController ()<UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *arrayGroup;
@property (nonatomic, strong) NSMutableArray *arrayContent;
@property (nonatomic, strong) NSMutableArray *arrUser;
@property (nonatomic, assign) NSInteger page;

@end

@implementation WSForumViewController
- (NSMutableArray *)arrayContent {
    if (!_arrayContent) {
        self.arrayContent = [NSMutableArray array];
    }
    return _arrayContent;
}
- (NSMutableArray *)arrayGroup {
    if (!_arrayGroup) {
        
        self.arrayGroup = [NSMutableArray array];
    }
    return _arrayGroup;
}
- (NSMutableArray *)arrUser {
    if (!_arrUser) {
        
        self.arrUser = [NSMutableArray array];
    }
    return _arrUser;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createTableView];
    [self createData];
}

- (void)createTableView {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 113) style:0];
    [self.tableView registerClass:[WSForumTableViewCell class] forCellReuseIdentifier:NSStringFromClass([WSForumTableViewCell class])];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.rowHeight = 95;
    [self.view addSubview:self.tableView];
    
}
- (void)getData {
    NSString *str = @"http://api.fit-time.cn/ftsns/loadGroupTopicPage?token=jORRrNqKMMZh%2FPZAX5NsF7JNvortgI1vUW71BT7ugcdsrFTIr%2BerBw%3D%3D";
    NSDictionary *dic = @{@"Host":@"api.fit-time", @"Content-Type":@"application/x-www-form-urlencoded", @"Accept":@"*/*", @"User-Agent":@"FitTime/1 CFNetwork/758.2.8 Darwin/15.0.0", @"Connection":@"keep-alive", @"Content-Length":@"31"};
    NSString *body = @"hot=2&page_index=0&page_size=20";
    
    [WSAFNetWorkingTool postWithURL:str body:body bodyType:BodyTypeJSONString httpHeader:dic responsType:ResponseTypeJSON progress:^(NSProgress *progress) {} success:^(id result) {
        
        NSArray *arrGroup = result[@"groupTopics"];
        
        for (NSDictionary *dic in arrGroup) {
            WSForumModel *model = [[WSForumModel alloc] initWithDic:dic];
            [self.arrayGroup addObject:model]; // 赞和评论的数组
            
            NSString *strContent = dic[@"content"];
            // 字符串转成字典
            NSDictionary *dicContent = [NSJSONSerialization JSONObjectWithData:[strContent dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
            WSForumModel *modelContent = [[WSForumModel alloc] initWithDic:dicContent];
            [self.arrayContent addObject:modelContent];
            
            NSString *url = [NSString stringWithFormat:@"http://api.fit-time.cn/ftuser/loadUserProfile?user_id=%@", model.userId];
            // uesr
            AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
            [manager GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                
                NSDictionary *dicUser = [responseObject objectForKey:@"user"];
                WSForumModel *model = [[WSForumModel alloc] initWithDic:dicUser];
                [self.arrUser addObject:model];
                [self.tableView reloadData];
                [self.tableView.mj_header endRefreshing];
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
                
            }];
            
            
        }
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
    } failure:^(NSError *error) {
        
        
    }];
    
}
- (void)getMoreData:(NSInteger)page {
    
    NSString *str = @"http://api.fit-time.cn/ftsns/loadGroupTopicPage?token=jORRrNqKMMZh%2FPZAX5NsF7JNvortgI1vUW71BT7ugcdsrFTIr%2BerBw%3D%3D";
    NSDictionary *dic = @{@"Host":@"api.fit-time", @"Content-Type":@"application/x-www-form-urlencoded", @"Accept":@"*/*", @"User-Agent":@"FitTime/1 CFNetwork/758.2.8 Darwin/15.0.0", @"Connection":@"keep-alive", @"Content-Length":@"31"};
    NSString *body1 = [NSString stringWithFormat:@"hot=2&page_index=%@&page_size=20", [NSString stringWithFormat:@"%ld", page]];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [WSAFNetWorkingTool postWithURL:str body:body1 bodyType:BodyTypeJSONString httpHeader:dic responsType:ResponseTypeJSON progress:^(NSProgress *progress) {
        
    } success:^(id result) {
        
        NSArray *arrGroup = [result objectForKey:@"groupTopics"];
        
        for (NSDictionary *dic in arrGroup) {
            WSForumModel *model = [[WSForumModel alloc] initWithDic:dic];
            [self.arrayGroup addObject:model]; // 赞和评论的数组
            NSString *strContent = [dic objectForKey:@"content"];
            // 字符串转成字典
            NSDictionary *dicContent = [NSJSONSerialization JSONObjectWithData:[strContent dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
            WSForumModel *modelContent = [[WSForumModel alloc] initWithDic:dicContent];
            [self.arrayContent addObject:modelContent];
            NSString *url = [NSString stringWithFormat:@"http://api.fit-time.cn/ftuser/loadUserProfile?user_id=%@", model.userId];
            // uesr
            [manager GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
                
                
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                
                NSDictionary *dicUser = [responseObject objectForKey:@"user"];
                WSForumModel *model = [[WSForumModel alloc] initWithDic:dicUser];
                [self.arrUser addObject:model];
                [self.tableView reloadData];
                [self.tableView.mj_footer endRefreshing];
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
                
            }];
            
        }
        [self.tableView reloadData];
        [self.tableView.mj_footer endRefreshing];
    } failure:^(NSError *error) {
    }];
    
}
- (void)createData {
    
    self.page = 0;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self getData];
        [self.tableView reloadData];
        
    }];
    [self.tableView.mj_header beginRefreshing];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        self.page = self.page + 1;
        [self getMoreData:self.page];
        [self.tableView reloadData];
    }];
    
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.arrayContent.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    WSForumTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([WSForumTableViewCell class])];
    
    WSForumModel *modelTitle = self.arrayContent[indexPath.row];
    WSForumModel *modelCom = self.arrayGroup[indexPath.row];
    if (self.arrUser.count == self.arrayContent.count) {
        WSForumModel *modelUse = self.arrUser[indexPath.row];
        cell.modelUse = modelUse;
    }
    cell.modelContent = modelTitle;
    cell.modelComPra = modelCom;
    
    return cell;
    
    
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    WSForumDetailsViewController *newInVC = [[WSForumDetailsViewController alloc] init];
    newInVC.modelContent = self.arrayContent[indexPath.row];
    newInVC.modelUse = self.arrUser[indexPath.row];
    newInVC.strID = [self.arrayGroup[indexPath.row] ID];
    [self.navigationController pushViewController:newInVC animated:YES];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
